package com.svo.weitu.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.ListView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.svo.platform.utils.HttpUtil;
import com.svo.platform.utils.SvoUtil;
import com.svo.platform.widget.LoadDialog;
import com.svo.weitu.MenuAdapter;
import com.svo.weitu.R;
import com.svo.weitu.activity.fragment.LineFragment;
import com.svo.weitu.activity.fragment.NieFragment;
import com.svo.weitu.activity.fragment.OrderFragment;
import com.svo.weitu.activity.fragment.UserCenterFragment;
import com.svo.weitu.model.MNew;
import com.svo.weitu.model.db.ResData;
import com.svo.weitu.model.entity.MenuEntity;
import com.svo.weitu.model.push.Utils;
import com.svo.weitu.util.Cons;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.UMShareAPI;

import java.util.List;

public class MainActivity extends SlidingFragmentActivity{
	private ListView listView;
	private MenuAdapter adapter;
	public static boolean showLeft;//刚进入页面时是显示左边还是右边
	List<MenuEntity> entities;
	SlidingMenu sm;
	private View headView;//顶部捏一捏
	private View footView;//底部订阅
	public static boolean isRefresh;
	UserCenterFragment userCenterFragment;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        showLeft = true;
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        setContentView(R.layout.activity_main);
		setBehindContentView(R.layout.fragment_channel_list);
		
		sm = getSlidingMenu();
		sm.setMode(SlidingMenu.LEFT_RIGHT);
		sm.setSlidingEnabled(true);
		sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);
		sm.setShadowWidthRes(R.dimen.shadow_width);
		sm.setShadowDrawable(R.drawable.shadow);
		sm.setBehindScrollScale(0.25f);
		sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
		
		sm.setSecondaryMenu(R.layout.user_center_fram);
		sm.setSecondaryShadowDrawable(R.drawable.shadowright);
		headView = LayoutInflater.from(this).inflate(R.layout.head_view, null);
		footView = LayoutInflater.from(this).inflate(R.layout.order_foot_view, null);
		headView.setOnClickListener(headViewListener);
		footView.setOnClickListener(footViewListener);
		findViewById(R.id.setting).setOnClickListener(settingListener);
		Fragment rightFragment = new LineFragment();
		getSupportFragmentManager().beginTransaction().replace(R.id.fram, rightFragment).commit();
		userCenterFragment = new UserCenterFragment();
		getSupportFragmentManager().beginTransaction().replace(R.id.user_center, userCenterFragment).commit();
		listView = (ListView) findViewById(R.id.channel_list);
		listView.addHeaderView(headView);
		listView.addFooterView(footView);
		refresh();
		if (entities == null || entities.size() == 0) {
			netReq(true);
		}else {
			if (showLeft) {
				fillRight();
			}
		}
		new MNew(this).checkNew(false,broadcastReceiver);//版本更新检查
    }

	private void netReq(final boolean isShowRight) {
		String qudao = Utils.getMetaValue(this, "UMENG_CHANNEL");
		int version = SvoUtil.getVersion(this);
		HttpUtil.get(Cons.gen+"res/getDefSub?qudao="+qudao+"&version="+version, null, new AsyncHttpResponseHandler(){
			@Override
			public void onStart() {
				super.onStart();
				if (loadDialog == null) {
					loadDialog = new LoadDialog(MainActivity.this);
				}
				loadDialog.show();
			}
			@Override
			public void onSuccess(String arg0) {
				super.onSuccess(arg0);
				if (loadDialog != null) {
					loadDialog.dismiss();
				}
				List<MenuEntity> lists = new Gson().fromJson(arg0, new TypeToken<List<MenuEntity>>(){}.getType());
				if (lists != null && lists.size() > 0) {
					ResData resData = new ResData(MainActivity.this);
					resData.insertSub(lists);
					refresh();
					if (isShowRight) {
						fillRight();
					}
				}
			}
			@Override
			public void onFailure(Throwable arg0, String arg1) {
				super.onFailure(arg0, arg1);
				if (loadDialog != null) {
					loadDialog.dismiss();
				}
			}
		});
	}
	public void refresh() {
		try {
			entities = new ResData(this).querySubAll();
			adapter = new MenuAdapter(MainActivity.this, entities);
			listView.setAdapter(adapter);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private LoadDialog loadDialog;
    @Override
    protected void onResume() {
    	super.onResume();
    	MobclickAgent.onResume(this);
    	if (isRefresh) {
			refresh();
			isRefresh = false;
		}
    	if (showLeft) {
    		showLeft = false;
    		listView.post(new Runnable() {
    			@Override
    			public void run() {
    				showMenu();
    			}
    		});
		}
    }
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
    	super.onWindowFocusChanged(hasFocus);
    	if (hasFocus && UserCenterFragment.isLoginClick) {
			UserCenterFragment.isLoginClick = false;
			if (userCenterFragment != null) {
				userCenterFragment.onResume();
			}
		}
    }
    public void onPause() {
    	super.onPause();
    	MobclickAgent.onPause(this);
    }
	public void showRight(Fragment fragment) {
		getSupportFragmentManager().beginTransaction().replace(R.id.fram, fragment).commit();
		showContent();
	}
	/**
	 * 
	 */
	private void fillRight() {
		try {
			showContent();
			LineFragment rightFragment = new LineFragment();
			Bundle args = new Bundle();
			MenuEntity entity = entities.get(0);
			args.putInt("type", entity .getType());
			args.putString("title", entity.getTitle());
			args.putInt("id", entity.getId());
			rightFragment.setArguments(args);
			getSupportFragmentManager().beginTransaction().replace(R.id.fram, rightFragment).commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	NieFragment rightFragment;
	private OnClickListener headViewListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			rightFragment = new NieFragment();
			getSupportFragmentManager().beginTransaction().replace(R.id.fram, rightFragment).commit();
			showContent();
		}
	};
	OnClickListener footViewListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			Fragment fragment = new OrderFragment();
			getSupportFragmentManager().beginTransaction().replace(R.id.fram, fragment).commit();
			showContent();
		}
	};
	OnClickListener settingListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			startActivity(new Intent(MainActivity.this, SetActivity.class));
			overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
		}
	};
//	long lastTime = 0;
	public void onBackPressed() {
//		QuitPopAd.getInstance().show(this);
		moveTaskToBack(true);
		/*long time = System.currentTimeMillis();
		if (time - lastTime < 1000) {
			super.onBackPressed();
		}else {
			lastTime = time;
			SvoToast.showHint(getApplicationContext(), "再按一次返回键退出", Toast.LENGTH_SHORT);
		}*/
	};
	protected void onActivityResult(int requestCode, int resultCode, android.content.Intent data) {
		if (resultCode != Activity.RESULT_OK) {
			return;
		}
		UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
		if (data != null) {
			Intent intent = new Intent(this,NieActivity.class);
			
			//取得返回的Uri,基本上选择照片的时候返回的是以Uri形式，但是在拍照中有得机子呢Uri是空的，所以要特别注意
			Uri mImageCaptureUri = data.getData();
			//返回的Uri不为空时，那么图片信息数据都会在Uri中获得。如果为空，那么我们就进行下面的方式获取
			if (mImageCaptureUri != null) {
				Bitmap image;
				try {
					//这个方法是根据Uri获取Bitmap图片的静态方法
					image = MediaStore.Images.Media.getBitmap(getContentResolver(), mImageCaptureUri);
					if (image != null) {
						intent.putExtra("from", "pick");
						intent.putExtra("uri", mImageCaptureUri);
						startActivity(intent);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				Bundle extras = data.getExtras();
				if (extras != null ) {
					final Bitmap image = extras.getParcelable("data");
					//这里是有些拍照后的图片是直接存放到Bundle中的所以我们可以从这里面获取Bitmap图片
					if (image != null) {
						new Thread(){
							public void run() {
								NieFragment.savePic(image, "/mnt/sdcard/Pictures", System.currentTimeMillis()+".jpg");
							};
						}.start();
						intent.putExtra("from", "camera");
						intent.putExtra("bitmap", image);
						startActivity(intent);
					}
				}
			}
		}
	};
	private BroadcastReceiver broadcastReceiver;

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (broadcastReceiver != null) {
			unregisterReceiver(broadcastReceiver);
		}
	}
}
